import type { Request, ResponseToolkit } from "@hapi/hapi";
import Hapi from "@hapi/hapi";
import { Routes } from "../../model/index";
interface treeItem {
  name: string;
  _id: string;
  path: string;
  parentId: string;
  children?: treeItem[];
}
function generateTree(data: treeItem[]) {
  let parents = data.filter((value) => value.parentId == "0");
  let children = data.filter((value) => value.parentId != "0");
  let generate = (parents: treeItem[], children: treeItem[]) => {
    parents.length &&
      parents.forEach((parent) => {
        children.length &&
          children.forEach((current, index) => {
            if (current.parentId == parent._id) {
              let temp = JSON.parse(JSON.stringify(children));
              temp.splice(index, 1);
              temp.length && (current.children = generate([current], temp));
              parent.children = parent.children || [];
              parent.children.push(current);
            }
          });
      });
    return parents;
  };
  return generate(parents, children);
}

let route: Hapi.ServerRoute<Hapi.ReqRefDefaults> = {
  path: "/menuTree",
  method: "get",
  handler: async (r: Request, h: ResponseToolkit) => {
    try {
      let list: any = await Routes.find();
      let tree: any = generateTree(JSON.parse(JSON.stringify(list)));
      return {
        code: 200,
        data: tree,
        message: "",
      };
    } catch (err: any) {
      return err;
    }
  },
  options: {
    plugins: {
      "hapi-swagger": {
        security: [{ apiKey: [] }],
      },
    },
    tags: ["api"],
  },
};
export default route;
